<template>
  <div>
    <label v-if="label">{{ label }}</label>
    <slot></slot>
    <p>{{ errorMsg }}</p>
  </div>
</template>

<script>
import Schema from 'async-validator'
export default {
  name: 'ElFormItem',
  props: {
    label: {
      type: String
    },
    prop: {
      type: String
    }
  },
  data() {
    return {
      errorMsg: ''
    }
  },
  inject: ['form'],
  mounted() {
    this.$on('validate', () => {
      this.validate()
    })
  },
  methods: {
    validate() {
      if (this.prop) {
        const rule = this.form.rules[this.prop]
        const newVal = this.form.model[this.prop]

        const descriptor = {
          [this.prop]: rule
        }
        const schema = new Schema(descriptor)

        return schema.validate({ [this.prop]: newVal }, (error) => {
          if (error) {
            this.errorMsg = error[0].message
          } else {
            this.errorMsg = ''
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped></style>
